// pages/profile/profile.js
const app = getApp()
const Toast = require('@vant/weapp/toast/toast')
const Dialog = require('@vant/weapp/dialog/dialog')
const { auth } = require('../../utils/auth')

Page({
  data: {
    // 主题相关
    theme: 'his', // 'his' | 'hers'
    themeColors: {
      his: {
        primary: '#D4AF37',
        secondary: '#B8860B',
        accent: '#FFD700',
        gradient: 'linear-gradient(135deg, #D4AF37 0%, #B8860B 100%)'
      },
      hers: {
        primary: '#FF69B4',
        secondary: '#FF1493',
        accent: '#FFB6C1',
        gradient: 'linear-gradient(135deg, #FF69B4 0%, #FF1493 100%)'
      }
    },
    
    // 页面状态
    loading: true,
    saving: false,
    
    // 用户信息
    userInfo: {
      id: '',
      nickname: '',
      avatarUrl: '',
      phone: '',
      email: '',
      gender: 0, // 0: 未设置, 1: 男, 2: 女
      bio: '',
      birthday: '',
      location: '',
      occupation: '',
      relationship: '', // 恋爱状态
      anniversary: '', // 纪念日
      createTime: '',
      lastLoginTime: '',
      role: 'his', // 'his' | 'hers'
      isAdmin: false, // 是否为管理员
      roleType: '', // 用户角色类型：ADMIN/PARTNER
      roleName: '' // 角色名称：管理员/伴侣
    },
    
    // 统计数据
    stats: {
      // 基础统计
      capsuleCount: 0,
      entryCount: 0,
      photoCount: 0,
      videoCount: 0,
      audioCount: 0,
      
      // 情感统计
      moodStats: {
        happy: 0,
        sad: 0,
        angry: 0,
        excited: 0,
        calm: 0,
        anxious: 0
      },
      
      // 活跃度统计
      activityStats: {
        totalDays: 0,
        activeDays: 0,
        streakDays: 0,
        longestStreak: 0,
        weeklyAverage: 0
      },
      
      // 互动统计
      interactionStats: {
        messagesExchanged: 0,
        photosShared: 0,
        momentsCreated: 0,
        gamesPlayed: 0,
        achievementsUnlocked: 0
      },
      
      // 健康统计（针对女性角色）
      healthStats: {
        cycleTracked: 0,
        symptomsLogged: 0,
        moodTracked: 0,
        predictionsAccuracy: 0
      },
      
      // 成长统计
      growthStats: {
        goalsSet: 0,
        goalsCompleted: 0,
        habitsFormed: 0,
        skillsLearned: 0,
        booksRead: 0
      }
    },
    
    // 数据洞察
    insights: {
      personalityProfile: {
        traits: [],
        strengths: [],
        growthAreas: []
      },
      emotionalPattern: {
        dominantMood: '',
        moodTrends: [],
        stressFactors: [],
        happinessTriggers: []
      },
      relationshipInsights: {
        communicationStyle: '',
        loveLanguage: '',
        compatibilityScore: 0,
        sharedInterests: [],
        growthOpportunities: []
      },
      recommendations: {
        activities: [],
        goals: [],
        improvements: []
      }
    },
    
    // UI状态
    showGenderPicker: false,
    showInsightsModal: false,
    showStatsModal: false,
    showSettingsModal: false,
    showAchievementsModal: false,
    activeTab: 'overview', // 'overview' | 'stats' | 'insights' | 'achievements'
    
    // 表单数据
    genderActions: [
      { name: '男', value: 1 },
      { name: '女', value: 2 }
    ],
    
    // 设置选项
    settings: {
      notifications: true,
      dataSync: true,
      privacyMode: false,
      autoBackup: true,
      shareAnalytics: false
    },
    
    // 成就系统
    achievements: {
      unlocked: [],
      locked: [],
      categories: [
        { id: 'love', name: '爱情达人', icon: '💕' },
        { id: 'memory', name: '回忆收藏家', icon: '📸' },
        { id: 'growth', name: '成长先锋', icon: '🌱' },
        { id: 'health', name: '健康守护者', icon: '💪' },
        { id: 'creativity', name: '创意大师', icon: '🎨' }
      ]
    }
  },

  onLoad(options) {
    this.initTheme()
    this.loadUserInfo()
    this.loadStats()
    this.loadInsights()
    this.loadAchievements()
    this.setData({ loading: false })
  },

  onShow() {
    this.refreshData()
  },

  onUnload() {
    // 清理定时器等资源
  },

  // 初始化主题
  initTheme() {
    const userRole = wx.getStorageSync('userRole') || 'his'
    this.setData({
      theme: userRole,
      'userInfo.role': userRole
    })
  },

  // 加载用户信息
  async loadUserInfo() {
    try {
      const userInfo = await app.globalData.auth.getUserInfo()
      if (userInfo) {
        // 获取用户角色信息
        const userRole = await auth.getUserRole()
        const isAdmin = await auth.isAdmin()
        
        this.setData({
          userInfo: {
            ...this.data.userInfo,
            ...userInfo,
            isAdmin: isAdmin,
            roleType: userRole?.roleType || '',
            roleName: userRole?.roleName || ''
          }
        })
        
        // 根据用户角色设置主题
        this.initTheme()
      }
    } catch (error) {
      console.error('加载用户信息失败:', error)
      Toast('加载用户信息失败')
    }
  },

  // 加载统计数据
  loadStats() {
    const stats = wx.getStorageSync('userStats') || {}
    const defaultStats = {
      capsuleCount: Math.floor(Math.random() * 50) + 10,
      entryCount: Math.floor(Math.random() * 200) + 50,
      photoCount: Math.floor(Math.random() * 100) + 20,
      videoCount: Math.floor(Math.random() * 30) + 5,
      audioCount: Math.floor(Math.random() * 40) + 8,
      
      moodStats: {
        happy: Math.floor(Math.random() * 30) + 20,
        sad: Math.floor(Math.random() * 10) + 2,
        angry: Math.floor(Math.random() * 5) + 1,
        excited: Math.floor(Math.random() * 25) + 15,
        calm: Math.floor(Math.random() * 35) + 25,
        anxious: Math.floor(Math.random() * 8) + 2
      },
      
      activityStats: {
        totalDays: Math.floor(Math.random() * 200) + 100,
        activeDays: Math.floor(Math.random() * 150) + 80,
        streakDays: Math.floor(Math.random() * 30) + 5,
        longestStreak: Math.floor(Math.random() * 60) + 20,
        weeklyAverage: Math.floor(Math.random() * 5) + 3
      },
      
      interactionStats: {
        messagesExchanged: Math.floor(Math.random() * 1000) + 500,
        photosShared: Math.floor(Math.random() * 200) + 100,
        momentsCreated: Math.floor(Math.random() * 80) + 30,
        gamesPlayed: Math.floor(Math.random() * 50) + 20,
        achievementsUnlocked: Math.floor(Math.random() * 20) + 5
      },
      
      healthStats: this.data.theme === 'hers' ? {
        cycleTracked: Math.floor(Math.random() * 12) + 6,
        symptomsLogged: Math.floor(Math.random() * 100) + 50,
        moodTracked: Math.floor(Math.random() * 200) + 100,
        predictionsAccuracy: Math.floor(Math.random() * 30) + 70
      } : {},
      
      growthStats: {
        goalsSet: Math.floor(Math.random() * 20) + 10,
        goalsCompleted: Math.floor(Math.random() * 15) + 8,
        habitsFormed: Math.floor(Math.random() * 10) + 5,
        skillsLearned: Math.floor(Math.random() * 8) + 3,
        booksRead: Math.floor(Math.random() * 15) + 5
      }
    }
    
    this.setData({
      stats: { ...this.data.stats, ...defaultStats, ...stats }
    })
  },

  // 加载数据洞察
  loadInsights() {
    const insights = wx.getStorageSync('userInsights') || {}
    const defaultInsights = {
      personalityProfile: {
        traits: this.data.theme === 'his' ? 
          ['理性思考', '目标导向', '责任感强', '善于规划'] :
          ['情感丰富', '直觉敏锐', '善于沟通', '富有创意'],
        strengths: this.data.theme === 'his' ? 
          ['逻辑分析', '决策能力', '执行力', '稳定性'] :
          ['共情能力', '创造力', '适应性', '人际关系'],
        growthAreas: this.data.theme === 'his' ? 
          ['情感表达', '灵活性', '创新思维'] :
          ['逻辑思维', '时间管理', '目标设定']
      },
      emotionalPattern: {
        dominantMood: this.data.theme === 'his' ? '平静' : '快乐',
        moodTrends: ['整体情绪稳定', '压力管理良好', '积极情绪占主导'],
        stressFactors: ['工作压力', '时间管理', '完美主义'],
        happinessTriggers: ['成就感', '陪伴时光', '新体验', '个人成长']
      },
      relationshipInsights: {
        communicationStyle: this.data.theme === 'his' ? '直接坦诚' : '温和体贴',
        loveLanguage: this.data.theme === 'his' ? '行动表达' : '言语肯定',
        compatibilityScore: Math.floor(Math.random() * 20) + 80,
        sharedInterests: ['旅行', '美食', '电影', '运动', '阅读'],
        growthOpportunities: ['增进沟通', '共同目标', '情感表达']
      },
      recommendations: {
        activities: [
          '每日情感分享时间',
          '周末户外活动',
          '共同学习新技能',
          '定期约会计划'
        ],
        goals: [
          '提升沟通质量',
          '建立共同兴趣',
          '增强情感连接',
          '规划未来目标'
        ],
        improvements: [
          '更多倾听和理解',
          '表达感激和赞美',
          '创造惊喜时刻',
          '保持个人成长'
        ]
      }
    }
    
    this.setData({
      insights: { ...this.data.insights, ...defaultInsights, ...insights }
    })
  },

  // 加载成就数据
  loadAchievements() {
    const achievements = wx.getStorageSync('userAchievements') || {}
    const allAchievements = [
      // 爱情达人类
      { id: 'love_1', category: 'love', name: '初次相遇', desc: '创建第一个时光胶囊', icon: '💕', unlocked: true },
      { id: 'love_2', category: 'love', name: '甜蜜时光', desc: '连续7天记录美好时刻', icon: '🍯', unlocked: true },
      { id: 'love_3', category: 'love', name: '爱的见证', desc: '创建50个时光胶囊', icon: '💖', unlocked: false },
      
      // 回忆收藏家类
      { id: 'memory_1', category: 'memory', name: '摄影师', desc: '上传100张照片', icon: '📸', unlocked: true },
      { id: 'memory_2', category: 'memory', name: '故事大王', desc: '记录50个故事', icon: '📚', unlocked: false },
      
      // 成长先锋类
      { id: 'growth_1', category: 'growth', name: '目标达成者', desc: '完成10个个人目标', icon: '🎯', unlocked: true },
      { id: 'growth_2', category: 'growth', name: '习惯养成', desc: '坚持一个习惯30天', icon: '🌱', unlocked: false },
      
      // 健康守护者类（女性专属）
      ...(this.data.theme === 'hers' ? [
        { id: 'health_1', category: 'health', name: '健康记录员', desc: '记录生理期3个月', icon: '💪', unlocked: true },
        { id: 'health_2', category: 'health', name: '自我关爱', desc: '完成50次情绪记录', icon: '🧘‍♀️', unlocked: false }
      ] : []),
      
      // 创意大师类
      { id: 'creativity_1', category: 'creativity', name: '创意火花', desc: '使用所有创作工具', icon: '🎨', unlocked: false },
      { id: 'creativity_2', category: 'creativity', name: '多媒体达人', desc: '创建音视频内容20个', icon: '🎬', unlocked: false }
    ]
    
    const unlocked = allAchievements.filter(a => a.unlocked)
    const locked = allAchievements.filter(a => !a.unlocked)
    
    this.setData({
      'achievements.unlocked': unlocked,
      'achievements.locked': locked
    })
  },

  // 刷新数据
  refreshData() {
    this.loadStats()
    this.loadInsights()
  },

  // 切换标签页
  onSwitchTab(e) {
    const { tab } = e.currentTarget.dataset
    this.setData({ activeTab: tab })
  },

  // 表单输入处理
  onNicknameChange(e) {
    this.setData({
      'userInfo.nickname': e.detail
    })
  },

  onPhoneChange(e) {
    this.setData({
      'userInfo.phone': e.detail
    })
  },

  onEmailChange(e) {
    this.setData({
      'userInfo.email': e.detail
    })
  },

  onBioChange(e) {
    this.setData({
      'userInfo.bio': e.detail
    })
  },

  onBirthdayChange(e) {
    this.setData({
      'userInfo.birthday': e.detail.value
    })
  },

  onLocationChange(e) {
    this.setData({
      'userInfo.location': e.detail
    })
  },

  onOccupationChange(e) {
    this.setData({
      'userInfo.occupation': e.detail
    })
  },

  onAnniversaryChange(e) {
    this.setData({
      'userInfo.anniversary': e.detail.value
    })
  },

  // 性别选择
  onSelectGender() {
    this.setData({ showGenderPicker: true })
  },

  onCloseGenderPicker() {
    this.setData({ showGenderPicker: false })
  },

  onGenderSelect(e) {
    const { value } = e.detail
    this.setData({
      'userInfo.gender': value,
      showGenderPicker: false
    })
  },

  // 头像更换
  onChangeAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        this.setData({
          'userInfo.avatarUrl': tempFilePath
        })
        Toast.success('头像更新成功')
      },
      fail: () => {
        Toast.fail('头像更新失败')
      }
    })
  },

  // 保存用户信息
  onSaveProfile() {
    this.setData({ saving: true })
    
    // 模拟保存过程
    setTimeout(() => {
      wx.setStorageSync('userInfo', this.data.userInfo)
      this.setData({ saving: false })
      Toast.success('保存成功')
    }, 1000)
  },

  // 显示洞察详情
  onShowInsights() {
    this.setData({ showInsightsModal: true })
  },

  // 显示统计详情
  onShowStats() {
    this.setData({ showStatsModal: true })
  },

  // 显示成就详情
  onShowAchievements() {
    this.setData({ showAchievementsModal: true })
  },

  // 显示设置
  onShowSettings() {
    this.setData({ showSettingsModal: true })
  },

  // 设置切换
  onToggleSetting(e) {
    const { setting } = e.currentTarget.dataset
    this.setData({
      [`settings.${setting}`]: !this.data.settings[setting]
    })
    wx.setStorageSync('userSettings', this.data.settings)
  },

  // 关闭弹窗
  onCloseModal() {
    this.setData({
      showInsightsModal: false,
      showStatsModal: false,
      showAchievementsModal: false,
      showSettingsModal: false
    })
  },

  // 角色管理
  onRoleManagement() {
    // 跳转到角色管理页面
    wx.navigateTo({
      url: '/pages/role-management/index'
    })
  },

  // 退出登录
  onLogout() {
    Dialog.confirm({
      title: '确认退出',
      message: '确定要退出登录吗？'
    }).then(() => {
      app.globalData.auth.logout()
      wx.reLaunch({
        url: '/pages/login/login'
      })
    }).catch(() => {})
  },

  // 工具函数
  formatDate(dateString) {
    if (!dateString) return '未知'
    const date = new Date(dateString)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  },

  getGenderText() {
    const genderMap = { 0: '未设置', 1: '男', 2: '女' }
    return genderMap[this.data.userInfo.gender] || '未设置'
  },

  getThemeStyle() {
    return this.data.themeColors[this.data.theme]
  },

  // 分享
  onShareAppMessage() {
    return {
      title: `${this.data.userInfo.nickname}的个人档案`,
      path: '/pages/profile/profile',
      imageUrl: this.data.userInfo.avatarUrl
    }
  }
})